﻿using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using PARK.Common.Helper;
using PARK.JsonSerialization;
using PARK.Accessctl.Interfaces.AccessCtl;
using PARK.Accessctl.Entitys;
using PARK.Accessctl.Entitys.Dto.AccessCtl;
using System.Text;
using System.Data;
using PARK.Accessctl.Entitys.Dto.AccessDoor;
using PARK.BussinCache.Interfaces;
using Newtonsoft.Json.Linq;

namespace PARK.Accessctl.AccessCtl
{
    /// <summary>
    /// 门禁设备服务
    /// </summary>
    [ApiDescriptionSettings(Tag = "Access", Name = "Ctl", Order = 200)]
    [Route("api/access/[controller]")]
    public class AccessCtlService : IAccessCtlService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<AccessCtlEntity> _accessCtlRepository;
        private readonly ISqlSugarRepository<AccessDoorEntity> _accessDoorRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;
        private readonly IUniubiSdkRepository _uniubiSdkRepository;

        /// <summary>
        /// 初始化一个<see cref="AccessCtlService"/>类型的新实例
        /// </summary>
        public AccessCtlService(
            ISqlSugarRepository<AccessCtlEntity> accessCtlRepository,
            ISqlSugarRepository<AccessDoorEntity> accessDoorRepository,
            IUserManager userManager,
            IUniubiSdkRepository uniubiSdkRepository)
        {
            _accessCtlRepository = accessCtlRepository;
            _db = _accessCtlRepository.Context;
            _accessDoorRepository = accessDoorRepository;
            _userManager = userManager;
            _uniubiSdkRepository=uniubiSdkRepository;
        }

        /// <summary>
        /// 获取门禁设备
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var entity = await _db.Queryable<AccessCtlEntity>().FirstAsync(p => p.CtlId == id);
            var output = entity.Adapt<AccessCtlInfoOutput>();
            var accessDoorList = await _db.Queryable<AccessDoorEntity>().Where(w => w.CtlId == entity.CtlId).ToListAsync();
            output.accessDoorList = accessDoorList.Adapt<List<AccessDoorInfoOutput>>();
            return output;
        }

        /// <summary>
		/// 获取门禁设备列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] AccessCtlListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if(userInfo!=null && userInfo.UserAdminFlag!=2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "ctlId" : input.sidx;
                var data = await _db.Queryable<AccessCtlEntity>()
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                    .Where(p => p.IsDeleted == 0)
                    .WhereIF(!string.IsNullOrEmpty(input.doorid), p => p.CtlId.Contains(input.doorid))
                    .WhereIF(!string.IsNullOrEmpty(input.keyword), p => p.CtlName.Contains(input.keyword) || p.CtlSn.Contains(input.keyword) || p.IoTcardNo.Contains(input.keyword))
                    .WhereIF(!string.IsNullOrEmpty(input.doorAreaId), p => p.DoorAreaId.Equals(input.doorAreaId))
                    .WhereIF(!string.IsNullOrEmpty(input.isOnline), p => p.IsOnline.Equals(input.isOnline))
                    .Select(it => new AccessCtlListOutput
                    {
                        ctlId = it.CtlId,
                        ctlName = it.CtlName,
                        ctlSn = it.CtlSn,
                        doorAreaId = it.DoorAreaId,
                        doorAreaName = it.DoorAreaName,
                        ctlposition = it.Ctlposition,
                        ioTcardNo = it.IoTcardNo,
                        ioTcardvalidity = it.IoTcardvalidity,
                        enabledMark = it.EnabledMark,
                        description = it.Description,
                        isOnline = it.IsOnline,
                        lastOnLineTime = it.LastOnLineTime,
                        isSyntime = it.IsSyntime,
                        lastSyntime = it.LastSyntime,
                        isAtt = it.IsAtt,
                        createSync = it.CreateSync
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<AccessCtlListOutput>.SqlSugarPageResult(data);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 新建门禁设备
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] AccessCtlCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = input.Adapt<AccessCtlEntity>();
                entity.CtlId = YitIdHelper.NextId().ToString();
                var data = await _db.Queryable<AccessCtlEntity>().Where(t => t.IsDeleted == 0 && t.CtlSn == entity.CtlSn && t.CompanyId == userInfo.companyId).ToListAsync();
                if (data.Count > 0)
                {
                    throw PARKException.Bah("所填写[设备SN]已存在!");
                }
                else
                {
                    try
                    {
                        //开启事务
                        _db.BeginTran();
                        //新增门禁设备记录
                        entity.Create();
                        entity.CompanyId = userInfo.companyId;
                        entity.CompanyName = userInfo.companyName;
                        // 调用宇泛接口
                        var dpfout = _uniubiSdkRepository.deviceCreate(entity.CtlSn, entity.CtlName, entity.CompanyId);
                        if (dpfout.code == "WO_SUS1000")
                        {
                            entity.CreateSync = 1;
                        }
                        var newEntity = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntityAsync();
                        var accessDoorEntityList = input.accessDoorList.Adapt<List<AccessDoorEntity>>();
                        if (accessDoorEntityList != null)
                        {
                            foreach (var item in accessDoorEntityList)
                            {
                                item.DoorId = YitIdHelper.NextId().ToString();
                                item.CtlId = newEntity.CtlId;
                                item.CompanyId = entity.CompanyId;
                                item.CompanyName = entity.CompanyName;
                            }
                            await _db.Insertable(accessDoorEntityList).ExecuteCommandAsync();
                        }
                        //关闭事务
                        _db.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                }
            }
            else
            {
                throw PARKException.Bah("您的权限无法操作!");
            }
        }


        /// <summary>
        /// 同步门禁设备
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("Sync/{id}")]
        public async Task CreateSync(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                //var entity = input.Adapt<AccessCtlEntity>();
                var entity = await _db.Queryable<AccessCtlEntity>().FirstAsync(t => t.CtlId == id && t.IsDeleted == 0);
                if (entity==null)
                {
                    throw PARKException.Bah("所填写[设备SN]不存在或已删除!");
                }
                else
                {
                    try
                    {
                        //开启事务
                        _db.BeginTran();
                        // 调用宇泛接口
                        var dpfout = _uniubiSdkRepository.deviceSync(entity.CtlSn, userInfo.companyId);
                        if (dpfout.code == "WO_SUS1000")
                        {
                            entity.CreateSync = 1;
                        }
                        else if(dpfout.code == "WO_EXP-100") //设备不存在
                        {
                            dpfout = _uniubiSdkRepository.deviceCreate(entity.CtlSn, entity.CtlName, entity.CompanyId);
                            if (dpfout.code == "WO_SUS1000")
                            {
                                entity.CreateSync = 1;
                            }
                            else
                            {
                                throw PARKException.Bah(dpfout.msg);
                            }
                        }
                        else
                        {
                            throw PARKException.Bah(dpfout.msg);
                        }
                        //更新门禁设备记录
                        await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                        //关闭事务
                        _db.CommitTran();
                        
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Bah(ex.Message);
                    }
                }
            }
            else
            {
                throw PARKException.Bah("您的权限无法操作!");
            }
        }

        /// <summary>
        /// 更新门禁设备
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task Update(string id, [FromBody] AccessCtlUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = input.Adapt<AccessCtlEntity>();
                var data = await _db.Queryable<AccessCtlEntity>().Where(t => t.IsDeleted == 0 && t.CtlSn == entity.CtlSn && t.CtlId != id && t.CompanyId == userInfo.companyId).ToListAsync();
                if (data.Count > 0)
                {
                    throw PARKException.Bah("所填写[设备SN]已存在!");
                }
                else
                {
                    try
                    {
                        //开启事务
                        _db.BeginTran();
                        entity.LastModify(id);
                        entity.CompanyId = userInfo.companyId;
                        entity.CompanyName = userInfo.companyName;

                        // 调用宇泛接口
                        var dpfout = _uniubiSdkRepository.deviceEdit(entity.CtlSn, entity.CtlName, entity.CompanyId);
                        if (dpfout.code == "WO_SUS1000")
                        {
                            entity.EditSync = 1;
                        }
                        //更新门禁设备记录
                        await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                        //清空原有数据
                        await _db.Deleteable<AccessDoorEntity>().Where(u => u.CtlId == id).ExecuteCommandAsync();
                        //新增新数据
                        var accessDoorEntityList = input.accessDoorList.Adapt<List<AccessDoorEntity>>();
                        if (accessDoorEntityList != null)
                        {
                            foreach (var item in accessDoorEntityList)
                            {
                                item.DoorId = YitIdHelper.NextId().ToString();
                                item.CtlId = entity.CtlId;
                                item.CompanyId = userInfo.companyId;
                                item.CompanyName = userInfo.companyName;
                            }
                            await _db.Insertable(accessDoorEntityList).ExecuteCommandAsync();
                        }
                        //关闭事务
                        _db.CommitTran();
                    }
                    catch (Exception ex)
                    {
                        //回滚事务
                        _db.RollbackTran();
                        throw PARKException.Oh(ErrorCode.COM1000);
                    }
                }
            }
            else
            {
                throw PARKException.Bah("您的权限无法操作!");
            }
        }
        /// <summary>
        /// 删除门禁设备
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<AccessCtlEntity>().FirstAsync(p => p.CtlId == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                try
                {
                    //开启事务
                    _db.BeginTran();
                    //删除门禁设备记录
                    await _db.Deleteable<AccessCtlEntity>().Where(d => d.CtlId == id).ExecuteCommandAsync();
                    //清空子表数据
                    await _db.Deleteable<AccessDoorEntity>().Where(u => u.CtlId == id).ExecuteCommandAsync();
                    // 调用宇泛接口
                    var dpfout = _uniubiSdkRepository.deviceDelete(entity.CtlSn, entity.CompanyId);
                    //关闭事务
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    //回滚事务
                    _db.RollbackTran();
                    throw PARKException.Oh(ErrorCode.COM1002);
                }
            }
            else
            {
                throw PARKException.Bah("您的权限无法操作!");
            } 
        }

        #region 获取门禁设备状态统计
        /// <summary>
        /// 获取门禁设备状态统计
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetCtlStatusCenQtys")]
        public async Task<dynamic> GetCtlStatusCenQtys([FromQuery] AccessCtlListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                try
                {
                    StringBuilder dbSql = new StringBuilder("select isOnline,count(0) as qty from access_ctl t where  IsDeleted=0 ");

                    #region 查询条件
                    if (!string.IsNullOrEmpty(input.doorAreaId))
                    {
                        dbSql.AppendFormat(" AND t.DoorAreaId= '{0}'", input.doorAreaId);
                    }
                    if (!string.IsNullOrEmpty(input.keyword))
                    {
                        dbSql.AppendFormat(" AND (t.CtlName like '%{0}%' or t.CtlSn like '%{0}%' or t.IoTcardNo like '%{0}%')", input.keyword);
                    }
                    #endregion

                    //公司权限
                    dbSql.AppendFormat(" and CompanyId='{0}'", userInfo.companyId);
                    dbSql.Append(" group by t.isOnline");
                    var data = await _db.SqlQueryable<DataTable>(dbSql.ToString()).ToDataTableAsync();
                    CtlStatusCenQtyOutput _output = new CtlStatusCenQtyOutput();
                    _output.onlineQty = 0;
                    _output.offlineQty = 0;
                    DataRow[] dr = data.Select("isOnline=0");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.offlineQty = int.Parse(dr[0]["qty"].ToString());
                    }
                    dr = data.Select("isOnline=1");
                    if (dr != null && dr.Length > 0)
                    {
                        _output.onlineQty = int.Parse(dr[0]["qty"].ToString());
                    }
                    return _output;
                }
                catch (Exception)
                {
                    throw PARKException.Oh("获取数据异常");
                }
            }
            else
            {
                return null;
            }  
        }
        #endregion

        /// <summary>
		/// 获取控制器列表
		/// </summary>
		/// <returns></returns>
        [HttpGet("GetTransferList")]
        public async Task<dynamic> GetTransferList()
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var data = await _db.Queryable<AccessCtlEntity>()
                .Where(p => p.CompanyId.Equals(userInfo.companyId))//权限
                 .Select(it => new AccessCtlTransferOutput
                 {
                     ctlId = it.CtlId,
                     ctlName = it.CtlName
                 }).MergeTable().ToListAsync();
                return data;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
		/// 获取控制器列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("GetCtlList")]
        public async Task<dynamic> GetCtlList([FromQuery] AccessDoorListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                StringBuilder dbsql = new StringBuilder("select b.ctlId,b.ctlSN,b.ctlName,b.doorAreaId,b.doorAreaName,b.ctlposition,b.isOnline,b.lastOnLineTime from access_ctl b ");
                dbsql.Append(" where b.IsDeleted=0 and b.EnabledMark=1");
                if (!string.IsNullOrEmpty(input.doorAreaId))
                {
                    dbsql.AppendFormat(" and b.doorAreaId='{0}'", input.doorAreaId);
                }
                if (!string.IsNullOrEmpty(input.keyword))
                {
                    dbsql.AppendFormat(" AND (b.CtlName like '%{0}%' or b.CtlSn like '%{0}%' or b.IoTcardNo like '%{0}%')", input.keyword);
                }
                //公司权限
                dbsql.AppendFormat(" and b.CompanyId='{0}'", userInfo.companyId);
                dbsql.Append(" order by b.doorAreaName, b.ctlName");
                var data = await _db.SqlQueryable<AccessDoorListOutput>(dbsql.ToString()).ToListAsync();
                return data;
            }
            else
            {
                return null;
            }
        }
    }
}
